import { JXDef } from "../../../conventions/JXCommon";
import { INVALID_VALUE, PRIORITY_VIEW } from "../../../Core/CoreDefine";
import { GCtrl } from "../../../Core/GCtrl";
import { GListView } from "../../../Core/GView/GListView";
import GViewBase from "../../../Core/GView/GViewBase";
import { BUFFINFO, CMsg, ITEM_DETAIL_FLAG, PART_BTL_SCENE, RedpointEffect, RPointMask } from "../../Common/Define";
import { JXColor } from "../../Common/JXColor";
import { LTimer } from "../../Common/Language";
import { VIEW_ID } from "../../Common/UI";
import { Res } from "../../Common/UIResources";
import { JXLocales } from "../../Common/Zh";
import RJXItem from "../../Data/RunTime/RunRaw/RJXItem";
import GameMgr from "../../Logic/GameMgr";
import JXItem from "../Common/JXItem";
import TowerFloorItem from "./TowerFloorItem";

const { ccclass, property, menu, executeInEditMode } = cc._decorator;

/** 多加载的塔层 */
const LOAD_OFFSET = 3;
/** 当前定位的塔层 */
const SHOW_OFFSET = 1;
@ccclass @menu('View/Home/TowerCtrl')
export default class TowerCtrl extends GViewBase {
    /** 层级列表容器 */
    @property(cc.Node) floorCnt: cc.Node = null;
    @property(cc.Node) coin: cc.Node = null;
    @property(cc.Node) jewel: cc.Node = null;
    @property(cc.Label) time: cc.Label = null;

    @property(cc.Sprite) press_btn: cc.Sprite = null;
    protected _listView: GListView = null;
    /**可以使用免费强征次数 */
    protected _freePress: number = 0;
    onGLoad() {
        GameMgr.redMgr.on(this.node, [
            { mask: [RPointMask.RPM_Tower], subPath: "bg/sportBottom/gain_btn", effectType: RedpointEffect.REDPOINT },
        ])
        this.assetImpl.prefab(Res.prefab.item.jxItem, () => {
            this.initItem();
            this._initEvents();
        })
    }

    onGStart(...args: any[]): void {
        this._initListView();
        let free = GameMgr.lUserData.getUserBuff(BUFFINFO.TowerFreeImpressNum);
        let freePress = GameMgr.lUserData.freePress;
        // console.log(GameMgr.lUserData.todayIsUseFreePressDate());
        this._freePress = free;
        if (!GameMgr.lUserData.todayIsUseFreePressDate()) {
            GameMgr.lUserData.freePress = 0;
            if (free > 0) {
                //换图
                this.assetImpl.spriteAtlasFrame(this.press_btn, Res.texture.views.tower, 'gain_btn');
            }
        } else {
            if (freePress < free) {
                this.assetImpl.spriteAtlasFrame(this.press_btn, Res.texture.views.tower, 'gain_btn');
            }
        }
    }

    protected _initEvents() {
        GCtrl.ES.on(CMsg.client.fight_ui.onFinishSettle, this, this.onCMSGBattleResult.bind(this), PRIORITY_VIEW);
        GCtrl.ES.on(CMsg.client.tower.onAddTowerReward, this, this.initItem.bind(this), PRIORITY_VIEW);
        GCtrl.ES.on(GCtrl.GTimerSecondEventMsg, this, this.setTime.bind(this), PRIORITY_VIEW);
    }

    onClose() {
        super.onClose();
    }

    protected initItem() {
        this.setTime();
        let coin = this.coin.getChildComByName("JXItem", JXItem);
        let jewel = this.jewel.getChildComByName("JXItem", JXItem);
        if (!coin) {
            coin = this.addGChild<JXItem>(Res.prefab.item.jxItem, this.coin);
            this.assetImpl.font(Res.font.fzcy, (font) => {
                coin.numLb.font = font;
                coin.numLb.node.color = JXColor.Cffffff;
                coin.numLb.node.addComponent(cc.LabelOutline);
                let LabelOutline = coin.numLb.node.getComponent(cc.LabelOutline);
                LabelOutline.color = JXColor.C000000;
                LabelOutline.width = 2;
            })
        }
        if (!jewel) {
            jewel = this.addGChild<JXItem>(Res.prefab.item.jxItem, this.jewel);

            this.assetImpl.font(Res.font.fzcy, (font) => {
                jewel.numLb.font = font;
                jewel.numLb.node.color = JXColor.Cffffff;
                jewel.numLb.node.addComponent(cc.LabelOutline);
                let LabelOutline = jewel.numLb.node.getComponent(cc.LabelOutline);
                LabelOutline.color = JXColor.C000000;
                LabelOutline.width = 2;
            })
        }
        let rJewel = new RJXItem([100, 3, GameMgr.lUserData.getRewardInfo()[1]]);
        let rCoin = new RJXItem([101, 3, GameMgr.lUserData.getRewardInfo()[0]]);
        coin.setView(rCoin, ITEM_DETAIL_FLAG.TPL | ITEM_DETAIL_FLAG.NO_BG | ITEM_DETAIL_FLAG.NUMPOS_ITEM_BC);
        jewel.setView(rJewel, ITEM_DETAIL_FLAG.TPL | ITEM_DETAIL_FLAG.NO_BG | ITEM_DETAIL_FLAG.NUMPOS_ITEM_BC);
    }

    protected setTime() {
        let info = GameMgr.lUserData.getTowerSpeed();
        let time = 0
        if (!info[0] || !info[1]) {
            time = 0;
        } else {
            time = GCtrl.now - GameMgr.lUserData.lastTowerGet;
        }
        this.time.string = LTimer(Math.round(time / 1000))
    }

    protected _initListView() {
        if (this._listView) return this._onListViewInited();
        this.assetImpl.prefab(Res.prefab.vw.home.TowerFloorItem, (floorPrefab) => {
            if (!this.isValid) return;
            let scrollView = this.floorCnt.parent.parent.getComponent(cc.ScrollView);
            this._listView = new GListView({
                scrollview: scrollView,
                mask: this.floorCnt.parent,
                content: this.floorCnt,
                itemTpl: cc.instantiate(floorPrefab),
                cbHost: this,
                itemSetter: this.onItemSetter,
                isCbClass: true,
                gapY: -10,
                padingX: 120,
                padingY: 10
            })
            this._onListViewInited();
        })
    }

    /**
 * 设置副本信息
 * @param item 层
 * @param lv 副本id
 */
    protected onItemSetter(item: TowerFloorItem, lv: number) {
        item.node.position = cc.v2(0)
        item.setView(lv);
    }

    protected _onListViewInited() {
        let typeInfo = GameMgr.towerData.getInfo();
        let curFloor = Math.max(typeInfo.min, GameMgr.lUserData.getLastTowerId() + 1);
        let levels = [];
        for (let i = Math.min(typeInfo.max, curFloor + LOAD_OFFSET); i >= typeInfo.min; i--) {
            levels.push(i);
        }
        this._listView.setData(levels);
        let showFloor = Math.min(curFloor + SHOW_OFFSET, typeInfo.max);
        this.scrollToCurFloor(showFloor, false);
    }


    /**
 * 设置当前副本
 * @param lv 副本ID
 */
    protected scrollToCurFloor(lv: number, withAction = true) {
        let index = this._listView.datas.indexOf(lv);
        if (index == INVALID_VALUE) {
            index = 0;
        };
        this._listView.scrollTo(index, withAction ? 1 : 0);
    }

    protected onCMSGBattleResult(_, result: { sceneId: number, isWin: boolean }) {
        if (result.sceneId != PART_BTL_SCENE.ARENA) return;
        let isWin = result.isWin;
        if (!isWin) {
            return;
        }
        let typeInfo = GameMgr.towerData.getInfo();
        let cur = GameMgr.lUserData.getLastTowerId();
        let curData = GameMgr.towerData.getRaw<STowerDataRaw>(cur);
        let arr = [curData.hook[0][2], curData.hook[1][2]];
        GameMgr.lUserData.addTowerSpeed(arr);
        let index = this._listView.datas.indexOf(cur);
        let item: TowerFloorItem = this._listView.tryGetItemByIndex(index);
        GameMgr.uiMgr.showBlockInput();
        item.onPass(() => {
            if (GameMgr.lUserData.getLastTowerId() + 1 > typeInfo.max) {
                // this._listView.refreshData();
                // GameMgr.uiMgr.hidBlockInput();
                // this.onClose();
                // GCtrl.ES.emit(CMsg.client.lltower.pass, this._curType);
                return;
            }

            let next = Math.min(typeInfo.max, GameMgr.lUserData.getLastTowerId() + 1);
            let levels = this._listView.datas;
            let oldMax = levels[0];
            let curMax = Math.min(next + LOAD_OFFSET, typeInfo.max);
            let showFloor = Math.min(next + SHOW_OFFSET, typeInfo.max);
            this.scrollToCurFloor(showFloor, true);
            cc.tween(this.node).delay(0.25).call(() => {
                let indexNext = this._listView.datas.indexOf(next);
                let itemNext: TowerFloorItem = this._listView.tryGetItemByIndex(indexNext);
                if (!itemNext) return;
                itemNext.onShow(() => {
                    let appends = [];
                    if (oldMax >= curMax) {
                        this._listView.refreshData();
                        GameMgr.uiMgr.hidBlockInput();
                        return;
                    }
                    for (let i = curMax; i > oldMax; i--) {
                        appends.push(i);
                    }
                    if (appends.length > 0) {
                        this._listView.insertData(0, ...appends);
                        this.scrollToCurFloor(showFloor, false);
                    }
                    GameMgr.uiMgr.hidBlockInput();
                });
            }).start();
        });
    }

    protected onFightBtnClick() {
        let lastPassId = GameMgr.lUserData.getLastTowerId();
        let info = GameMgr.towerData.getInfo();
        if (lastPassId + 1 > info.max) {
            return GameMgr.uiMgr.showToast(JXLocales.tower.isTop);
        }
        let isNoHero = GameMgr.rHeroData.checkInNoHero();
        if (isNoHero) {
            GameMgr.uiMgr.showToast(JXLocales.fight.teamEmpty);
            return;
        }
        GCtrl.ES.emit(CMsg.client.tower.onStartFight, lastPassId + 1);
    }


    protected onGetItemClick() {
        let info = GameMgr.lUserData.getRewardInfo();
        if (!info[0] && !info[1]) {
            GameMgr.uiMgr.showToast(JXLocales.tower.noReward);
            return;
        }
        let reward = [[100, 3, info[1]], [101, 3, info[0]]]
        GameMgr.lUserData.getTowerReward();
        this.initItem();
        GameMgr.jumpToMgr.jumpGoTo(VIEW_ID.rewardCtrl, reward);
        GameMgr.redMgr.sendValueSettingMsg(RPointMask.RPM_Tower, false);
    }

    protected onPressBtnClick(): void {
        let free = GameMgr.lUserData.freePress;
        let speed = GameMgr.lUserData.getTowerSpeed();
        if (!speed[0] || !speed[1]) {
            return GameMgr.uiMgr.showToast(JXLocales.tower.noReward);
        }
        if (free < this._freePress) {
            GameMgr.lUserData.useFreePress();
            let min = GameMgr.systemConfig.value<number>(JXDef.SYS_CONFIG_KEY.towerPressTime);
            let reward = [[100, 3, speed[1] * min], [101, 3, speed[0] * min]]
            GameMgr.jumpToMgr.jumpGoTo(VIEW_ID.rewardCtrl, reward);
            let free2 = GameMgr.lUserData.freePress;
            if (free2 == this._freePress) {
                //换看视频图
                this.assetImpl.spriteAtlasFrame(this.press_btn, Res.texture.views.tower, 'press_btn');
            }
        } else {
            GameMgr.sdkMgr.watchAd(() => {

                let min = GameMgr.systemConfig.value<number>(JXDef.SYS_CONFIG_KEY.towerPressTime);
                let reward = [[100, 3, speed[1] * min], [101, 3, speed[0] * min]]
                GameMgr.jumpToMgr.jumpGoTo(VIEW_ID.rewardCtrl, reward);
                let free2 = GameMgr.lUserData.freePress;
                if (free2 == this._freePress) {
                    //换看视频图
                    this.assetImpl.spriteAtlasFrame(this.press_btn, Res.texture.views.tower, 'press_btn');
                }
            })
        }
    }
}   